<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <i class="fas fa-arrow-left" @click="goBack"></i>
      <p>{{ categoryName }}商家</p>
      <div style="width: 24px;"></div> <!-- 占位用于对称 -->
    </header>

    <!-- 商家列表部分 -->
    <ul class="business">
      <li
          v-for="business in filteredBusinesses"
          :key="business.id"
          @click="toBusinessInfo(business.id)"
          class="business-item"
      >
        <div class="business-img">
          <img :src="getBusinessImage(business.businessImg)" />
          <div class="business-img-quantity" v-if="getCartQuantity(business.id) > 0">
            {{ getCartQuantity(business.id) }}
          </div>
        </div>
        <div class="business-info">
          <h3>{{ business.businessName }}</h3>
          <div class="business-rating">
            <div class="stars">
              <i
                  v-for="n in 5"
                  :key="n"
                  class="fas fa-star"
                  :class="{ filled: n <= Math.floor(business.rating || 0) }"
              ></i>
              <span class="rating-score">{{ business.rating || 0 }}</span>
            </div>
            <span class="month-sales">月售{{ business.monthSales || 0 }}</span>
          </div>
          <p class="delivery-info">
            &#165;{{ business.startPrice }}起送 | &#165;{{ business.deliveryPrice }}配送
          </p>
          <p class="business-explain">{{ business.businessExplain }}</p>
          <div class="business-tags">
            <span v-if="business.deliveryType" class="tag delivery-tag">{{ business.deliveryType }}</span>
            <span v-if="business.tags" v-for="tag in business.tags.slice(0, 2)" :key="tag" class="tag">
              {{ tag }}
            </span>
          </div>
          <div class="business-activities">
            <span
                v-for="(activity, index) in business.activities?.slice(0, 1)"
                :key="index"
                class="activity"
            >
              {{ activity.content }}
            </span>
            <span v-if="business.activities && business.activities.length > 1" class="activity-more">
              还有{{ business.activities.length - 1 }}个活动
            </span>
          </div>
        </div>
      </li>
    </ul>

    <!-- 加载状态 -->
    <div class="loading" v-if="loading">
      <i class="fas fa-spinner fa-spin"></i>
      <span>加载中...</span>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-if="!loading && businesses.length === 0">
      <i class="fas fa-store"></i>
      <p>暂无商家</p>
    </div>

    <!-- 底部菜单部分 -->
    <Footer></Footer>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { businessAPI } from '@/api/business.js';
import { cartAPI } from '@/api/cart.js';
import Footer from "../components/Footer.vue";

const route = useRoute();
const router = useRouter();

const orderTypeId = ref(route.query.orderTypeId);
const businesses = ref([]);
const cartItems = ref([]);
const loading = ref(false);

// 分类名称映射
const categoryMap = {
  '1': '美食',
  '2': '早餐',
  '3': '跑腿代购',
  '4': '汉堡披萨',
  '5': '甜品饮品',
  '6': '速食简餐',
  '7': '地方小吃',
  '8': '米粉面馆',
  '9': '包子粥铺',
 // '10': '炸鸡炸串'
};

// 计算分类名称
const categoryName = computed(() => {
  return categoryMap[orderTypeId.value] || '商家';
});

// 计算属性：筛选后的商家列表
const filteredBusinesses = computed(() => {
  if (orderTypeId.value === 'all') {
    return businesses.value;
  }
  return businesses.value.filter(business =>
      business.orderTypeId === orderTypeId.value
  );
});

// 页面加载时获取数据
onMounted(async () => {
  await loadBusinesses();
  await loadCartItems();
});

// 加载商家列表
const loadBusinesses = async () => {
  loading.value = true;
  try {
    const response = await businessAPI.getBusinesses();

    // 根据API响应结构调整
    if (response.data && response.data.success === true && response.data.data) {
      businesses.value = response.data.data;
    } else if (response.data) {
      businesses.value = response.data;
    }

    // 添加模拟数据
    businesses.value.forEach(business => {
      business.rating = parseFloat((Math.random() * 2 + 3).toFixed(1));
      business.monthSales = Math.floor(Math.random() * 1000) + 100;
      business.deliveryType = Math.random() > 0.3 ? '蜂鸟专送' : null;
      business.tags = ['品质优选', '回头客多'].slice(0, Math.floor(Math.random() * 2) + 1);
      business.activities = [
        { content: '新用户立减15元' },
        { content: '满30减5元' }
      ].slice(0, Math.floor(Math.random() * 2) + 1);
    });

  } catch (error) {
    console.error('获取商家列表失败:', error);
    alert('获取商家列表失败');
  } finally {
    loading.value = false;
  }
};

// 加载购物车商品
const loadCartItems = async () => {
  try {
    const response = await cartAPI.getCartItems();
    if (response.data && response.data.success === true && response.data.data) {
      cartItems.value = response.data.data;
    } else if (response.data) {
      cartItems.value = response.data;
    }
  } catch (error) {
    console.error('获取购物车失败:', error);
  }
};

// 获取商家图片
const getBusinessImage = (imagePath) => {
  if (!imagePath) {
    const images = [
      require('@/assets/sj01.png'),
      require('@/assets/sj02.png'),
      require('@/assets/sj03.png'),
      require('@/assets/sj04.png'),
      require('@/assets/sj05.png')
    ];
    return images[Math.floor(Math.random() * images.length)];
  }
  return imagePath;
};

// 获取购物车中某个商家的商品数量
const getCartQuantity = (businessId) => {
  const businessCartItems = cartItems.value.filter(item =>
      item.businessId === businessId || item.foodDetails?.businessId === businessId
  );
  return businessCartItems.reduce((total, item) => total + (item.quantity || 0), 0);
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 跳转到商家详情
const toBusinessInfo = (businessId) => {
  router.push({
    path: '/businessInfo',
    query: { businessId }
  });
};
</script>

<style scoped>
.wrapper {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
}

/* Header样式 */
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4vw;
  box-sizing: border-box;
}

.wrapper header i {
  font-size: 5vw;
  cursor: pointer;
}

.wrapper header p {
  margin: 0;
  font-weight: bold;
}

/* 商家列表样式 */
.wrapper .business {
  width: 100%;
  margin-top: 12vw;
  margin-bottom: 14vw;
}

.wrapper .business .business-item {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw;
  border-bottom: solid 1px #eee;
  background-color: white;
  user-select: none;
  cursor: pointer;
  display: flex;
  align-items: flex-start;
  transition: background-color 0.2s;
}

.wrapper .business .business-item:hover {
  background-color: #f9f9f9;
}

.wrapper .business .business-item .business-img {
  position: relative;
  margin-right: 4vw;
}

.wrapper .business .business-item .business-img img {
  width: 20vw;
  height: 20vw;
  border-radius: 2vw;
  object-fit: cover;
}

.wrapper .business .business-item .business-img .business-img-quantity {
  width: 6vw;
  height: 6vw;
  background-color: #ff4757;
  color: #fff;
  font-size: 3vw;
  border-radius: 3vw;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  right: -1.5vw;
  top: -1.5vw;
  font-weight: bold;
}

.wrapper .business .business-item .business-info {
  flex: 1;
}

.wrapper .business .business-item .business-info h3 {
  font-size: 4.2vw;
  color: #333;
  margin: 0 0 2vw 0;
  font-weight: bold;
}

.wrapper .business .business-item .business-info .business-rating {
  display: flex;
  align-items: center;
  margin-bottom: 2vw;
}

.wrapper .business .business-item .business-info .business-rating .stars {
  display: flex;
  align-items: center;
  margin-right: 3vw;
}

.wrapper .business .business-item .business-info .business-rating .stars i {
  font-size: 3vw;
  color: #ddd;
  margin-right: 0.5vw;
}

.wrapper .business .business-item .business-info .business-rating .stars i.filled {
  color: #ffb400;
}

.wrapper .business .business-item .business-info .business-rating .stars .rating-score {
  font-size: 3vw;
  color: #ffb400;
  margin-left: 1vw;
  font-weight: bold;
}

.wrapper .business .business-item .business-info .business-rating .month-sales {
  font-size: 3vw;
  color: #666;
}

.wrapper .business .business-item .business-info .delivery-info {
  font-size: 3.2vw;
  color: #666;
  margin: 0 0 2vw 0;
}

.wrapper .business .business-item .business-info .business-explain {
  font-size: 3.2vw;
  color: #999;
  margin: 0 0 2vw 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.wrapper .business .business-item .business-info .business-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 1vw;
  margin-bottom: 2vw;
}

.wrapper .business .business-item .business-info .business-tags .tag {
  font-size: 2.5vw;
  color: #666;
  border: 1px solid #eee;
  padding: 0.5vw 1.5vw;
  border-radius: 1vw;
}

.wrapper .business .business-item .business-info .business-tags .delivery-tag {
  background-color: #0097ff;
  color: white;
  border-color: #0097ff;
}

.wrapper .business .business-item .business-info .business-activities {
  display: flex;
  flex-wrap: wrap;
  gap: 1vw;
}

.wrapper .business .business-item .business-info .business-activities .activity {
  font-size: 2.8vw;
  color: #ff5339;
  background: #fff0ef;
  padding: 0.5vw 1.5vw;
  border-radius: 1vw;
}

.wrapper .business .business-item .business-info .business-activities .activity-more {
  font-size: 2.8vw;
  color: #999;
}

/* 加载状态 */
.loading {
  text-align: center;
  padding: 10vw;
  color: #999;
  background: white;
  margin: 12vw 0 14vw 0;
}

.loading i {
  font-size: 8vw;
  margin-bottom: 3vw;
}

.loading span {
  font-size: 3.5vw;
  display: block;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 20vw 4vw;
  color: #999;
  background: white;
  margin: 12vw 0 14vw 0;
}

.empty-state i {
  font-size: 15vw;
  margin-bottom: 4vw;
}

.empty-state p {
  font-size: 4vw;
  margin: 0;
}
</style>